<template>
  <div>
    <SearchContainer @search="getDataSource" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item label="" name="mcbm">
          <a-input v-model:value="formState.mcbm" class="w-64" placeholder="单号/物品名称/助记码/物品编号" />
        </a-form-item>
        <a-form-item label="日期范围" name="dateRange">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="出库仓库" name="ckckmc" class="w-72">
          <SelectWarehouse v-model:value="formState.ckckmc" multiple class="w-64" :max-tag-count="1" :max-tag-text-length="5" />
        </a-form-item>
        <a-form-item label="入库仓库" name="rkckmc" class="w-72">
          <SelectWarehouse v-model:value="formState.rkckmc" multiple :max-tag-count="1" :max-tag-text-length="5" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex justify-start">
        <a-button class="mb-2 mr-2" type="primary" @click="onAdd"> 新增 </a-button>
        <BaseExport
          type="物资"
          name="移动单"
          code="000262"
          :search-params="{
            ...formState.value,
            stdate: formState.dateRange?.[0],
            eddate: formState.dateRange?.[1]
          }"
          >导出</BaseExport
        >
      </div>
      <BaseTable
        :data-source="dataSource"
        fill
        :expanded-row-keys="expandedRowKeys"
        :loading="loading"
        :scroll="{ x: 1800 }"
        column-code="000262"
        :pagination="{ total: page.total, current: page.current, pageSize: page.pageSize }"
        @change="onPageChange"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'djlbStr'">
            {{ record.djlb === 0 ? '药材' : '物资' }}
          </template>
          <template v-if="column.dataIndex === 'qrztStr'">
            <a-tag v-if="record.qrzt === 0" color="blue">待确认</a-tag>
            <a-tag v-if="record.qrzt === 1" color="green">已确认</a-tag>
            <a-tag v-if="record.qrzt === 2" color="red">已作废</a-tag>
          </template>
          <template v-if="column.dataIndex === 'zydh'">
            <PopoverTable :config="detailConfig" :params="{ zydh: record.zydh }" :width="1600">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'mc'">
                  <MedicineInfo :value="{ mc: popRecord.mc, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
              </template>
              {{ record.zydh }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'ckfsStr'">
            <span v-if="record.ckfs === 0">直接出库</span>
            <span v-if="record.ckfs === 1">申请单出库</span>
            <span v-if="record.ckfs === 2">调拨单出库</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" :disabled="record.qrzt === 1" @click="onDetail(record)">明细</a-button>
              <BaseButton confirm-text="是否确认?" type="link" size="small" :disabled="record.qrzt === 1" @click="onConfirm(record)"> 确认 </BaseButton>
              <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button>
              <a-button type="link" size="small" @click="onExport(record)">导出</a-button>
              <TableMoreButton>
                <a-button type="link" size="small" :disabled="record.qrzt === 1" @click="onEdit(record)">修改</a-button>
                <!-- <a-button type="link" size="small" :disabled="record.qrzt === 1" @click="onConfirm(record)">确认</a-button> -->
                <BaseButton confirm-text="是否作废此移动单?" type="text" danger size="small" :disabled="record.qrzt === 1" @click="onClickCancel(record)">
                  作废
                </BaseButton>
              </TableMoreButton>
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <AddModal v-model:open="open" :row-data="rowData" @ok="getDataSource" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import SearchContainer from '@/components/SearchContainer'
import SelectWarehouse from '@/components/SelectWarehouse'
import { post, http } from '@/utils/request'
import BaseTable from '@/components/BaseTable'

import useUserStore from '@/store/user'
import AddModal from './AddModal.vue'

const { empName } = useUserStore()

const router = useRouter()
const rowData = ref(null)
const formRef = ref(null)
const dataSource = ref([])

const open = ref(false)
const loading = ref(false)

const formState = ref({
  dateRange: [dayjs(new Date().setDate(new Date().getDate() - 10)).format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  pxlx: '',
  pxzd: ''
})
const detailConfig = ref({
  url: '/materials/psiform/getTransferFormDetailList',
  columnCode: '000149',
  rowKey: 'lsh',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})
const page = ref({
  total: 0,
  current: 1,
  pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
})

const onDetail = (record) => {
  router.push({
    path: '/material/warehouse/move-detail',
    query: {
      zydh: record.zydh
    }
  })
}
const onClickCancel = async (record) => {
  const { code, msg } = await post('/materials/psiform/doCancelTransferForm', {
    zydh: record.zydh
  })
  if (code !== 0) return message.error(msg || '作废失败')
  getDataSource()
  message.success('作废成功')
}

const onEdit = (record) => {
  rowData.value = Object.assign({}, record)
  open.value = true
}
const onAdd = () => {
  rowData.value = null
  open.value = true
}
const getDataSource = async () => {
  loading.value = true
  const { data, code, total } = await post(
    '/materials/psiform/getTransferFormHeadList',
    {
      ...formState.value,
      pageNum: page.value.current,
      pageSize: page.value.pageSize,
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1]
    },
    { loading: true }
  )
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    page.value.total = total
  }
}
const onConfirm = async (record) => {
  const { code, msg } = await post('/materials/psiform/doConfirmTransferForm', {
    dh: record.zydh,
    qrr: empName
  })

  if (code !== 0) return message.error(msg || '确认失败')
  getDataSource()
  message.success('确认成功')
}
const onPageChange = ({ current, pageSize }, filters, sorter) => {
  page.value.current = current
  page.value.pageSize = pageSize
  if (sorter.column?.dataIndex) {
    formState.value.pxlx = sorter.order === 'ascend' ? '1' : '2'
    if (sorter.column.dataIndex === 'yddh') {
      formState.value.pxzd = '1'
    } else if (sorter.column.dataIndex === 'qrsj') {
      formState.value.pxzd = '2'
    } else {
      formState.value.pxzd = '3'
    }
  } else {
    formState.value.pxlx = ''
  }
  getDataSource()
}

const onPrint = async (row) => {
  const { code, msg, data } = await post('/materials/psiform/printMtrKcZydzbList', { zydh: row.zydh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 导出
const onExport = (row) => {
  http
    .post(
      '/materials/export',
      {
        parameters: {
          zydh: row.zydh
        },
        tblcode: '000149'
      },
      { responseType: 'blob' }
    )
    .then((res) => {
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = '移动单明细' + '.xlsx'
      element.href = href
      element.click()
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}

onMounted(() => {
  getDataSource()
})
</script>
